package com.yisa.person.service;

import cn.hutool.json.JSONObject;
import com.mongodb.client.result.UpdateResult;
import com.yisa.person.entity.FaceGroup;
import com.yisa.person.entity.User;
import com.yisa.person.mongo.BatchUpdateOptions;
import com.yisa.person.utils.Base64Util;
import com.yisa.person.utils.BathUpdateUtil;
import com.yisa.person.utils.HutoolUtil;
import com.yisa.person.utils.MongoUtil;
import lombok.extern.slf4j.Slf4j;
import net.anumbrella.seaweedfs.core.FileTemplate;
import net.anumbrella.seaweedfs.core.file.FileHandleStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FaceGroupService {

    @Value("${mongo.collectionName}")
    private String mongoCollection;
    @Value("${weed.collectionName}")
    private String weedCollectionName;
    @Value("${weed.ttl}")
    private String weedTTL;

    @Value("${mongo.limitNum}")
    private int limitNum;
    @Value("${mongo.sortBy}")
    private int sortBy;

    @Resource
    private MongoTemplate mongoTemplate;

    @Autowired
    private FileTemplate fileTemplate;


    public void test() {
//        mongoUtil.createCollection("face_group");

        /**
         * 插入【多条】文档数据，如果文档信息已经【存在就抛出异常】
         *
         * @return 插入的多个文档信息
         */
        // 使用户信息加入结合
        List<FaceGroup> userList = new ArrayList<>();


        for (Long i = 2000L; i < 2000000; i++) {
            // 设置用户信息
            FaceGroup user3 = new FaceGroup()
                    .setId(i)
                    .setPersonId("345")
                    .setPersonnelIdNumber("345")
                    .setHouseholdAddress("345")
                    .setStatus(0);
            userList.add(user3);
        }


        // 插入一条用户数据，如果某个文档信息已经存在就抛出异常
        Collection<FaceGroup> newUserList = mongoTemplate.insert(userList, "face_group");
        // 输出存储结果
        for (FaceGroup user : newUserList) {
            log.info("存储的用户信息为：{}", user);
        }
    }

    public void updateData() {
        //回写信息
        // 创建条件对象
        Criteria criteriaStatus = Criteria.where("status").is(1);
        // 创建条件对象，将上面条件进行 AND 关联
        Criteria criteria = new Criteria().andOperator(criteriaStatus);
        // 创建查询对象，然后将条件对象添加到其中
        Query query = new Query(criteria);

        // 创建更新对象,并设置更新的内容
        Update update = new Update()
                .set("status", 0)
                .set("personnel_name", "123")
                .set("personnel_id_number", "234")
                .set("personnel_photo_url", "456")
                .set("gender", 1)
                .set("birthday", 1)
                .set("household_address", "21345");

        // 执行更新
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, FaceGroup.class, "face_group");
    }




    /**
     * 根据【单个条件】查询集合中的文档数据，并【限制指定数目】
     *
     * @return 符合条件的文档列表
     */
    public List<FaceGroup> findNotUpdateData() {
        // 创建条件
        Criteria criteria = Criteria.where("status").is(0);
        // 创建查询对象，然后将条件对象添加到其中
        Query query = new Query(criteria).limit(limitNum);

        if (sortBy == 1) {
            query.with(Sort.by(Sort.Direction.DESC, "_id"));
        }

        // 执行查询
        return mongoTemplate.find(query, FaceGroup.class, mongoCollection);
    }


    public void updateData(List<JSONObject> personInfoList) {
        List<BatchUpdateOptions> list = new ArrayList<BatchUpdateOptions>();
        for (JSONObject personInfo : personInfoList) {

            // 将base64保存到weed
            personInfo.set("savePhoto", savePhoto(personInfo));

            // 创建更新对象,并设置更新的内容
            Update update = new Update()
                    .set("status", 1)
                    .set("personnel_name", personInfo.getStr("PersonName"))
                    .set("personnel_id_number", personInfo.getStr("PersonIdNumber"))
                    .set("gender", HutoolUtil.judgeGender(personInfo.getStr("PersonIdNumber")))
                    .set("birthday", Long.valueOf(personInfo.getStr("PersonIdNumber").substring(6, 14)));
            //如果weed保存失败，继续用原来的Url
            if (personInfo.getBool("savePhoto")) {
                update.set("personnel_photo_url", personInfo.getStr("savePath"));
            }

            String address = personInfo.getStr("HJDXZ");
            if (StringUtils.isNotBlank(address)) {
                update.set("household_address", address);
            }

            Query query = Query.query(Criteria.where("_id").is(personInfo.get("id")));
            BatchUpdateOptions options = new BatchUpdateOptions(query, update, false, true);
            list.add(options);
        }

        if (list.size() > 0) {
            int n = BathUpdateUtil.batchUpdate(mongoTemplate, mongoCollection, list, true);

            // 输出结果信息
            String resultInfo = "共匹配到" + list.size() + "条数据,修改了" + n + "条数据";
            log.warn("更新结果：{}", resultInfo);
        }

        log.warn("------------------");
    }

    private boolean savePhoto(JSONObject personInfo) {

        String personIdNumber = personInfo.getStr("PersonIdNumber");
        String personPhotoData = personInfo.getStr("PersonPhotoData");
        String personID = personInfo.getStr("PersonID");

        //存weed
        try {
            fileTemplate.setCollection(weedCollectionName);
            fileTemplate.setTimeToLive(weedTTL);
            FileHandleStatus fileHandleStatus = fileTemplate.saveFileByStream(personIdNumber + "_" + personID + "_" + System.currentTimeMillis(),
                    Base64Util.Base64ToInputStream(personPhotoData));

            personInfo.set("savePath", fileHandleStatus.getFileUrl());

            return true;
        } catch (Exception e) {
            log.error("image存储失败：{}", e.getMessage());
            return false;
        }
    }

}
